
package com.yimixian.app.address;

import com.yimixian.app.R;
import com.yimixian.app.SystemFramework;
import com.yimixian.app.activity.YMXMainActivity;
import com.yimixian.app.common.CacheKeys;
import com.yimixian.app.common.Constants;
import com.yimixian.app.common.SharePreferenceKeys;
import com.yimixian.app.data.DataManager;
import com.yimixian.app.model.Address;
import com.yimixian.app.model.User;
import com.yimixian.app.util.SharedPreferencesHelper;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import butterknife.ButterKnife;
import butterknife.InjectView;

public class AddressShowFragment extends Fragment {

    @InjectView(R.id.address_view)
    AddressViewForCart mAddressView;
//    private Integer mLastSavedStoreType;
    public DataManager mDataManager;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_address_show, container, false);
        ButterKnife.inject(this, view);
        mDataManager = DataManager.getInstance();
        if (isAddressEmpty()) {
            mAddressView.showNodata();
        } else {
            Address mAddress = SharedPreferencesHelper.getAddress(SharePreferenceKeys.CURRENT_ADDRESS);
            if (mAddress != null && !mAddress.isPickup){
                mAddressView.bind(mAddress);
            } else {
                User user = mDataManager.<User> get(CacheKeys.CURRENT_USER);
                if (user != null) {
                    mAddressView.bind(SharedPreferencesHelper.getPickUpStoreName(), user.tel);
                }
            }
        }
        mAddressView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                jumpAddress();
            }
        });

        return view;
    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
    }

    @Override
    public void onDetach() {
        super.onDetach();
    }

    public void jumpAddress() {

        Intent intent = new Intent(SystemFramework.getInstance().getGlobalContext(),
                ChooseAddressOrStoreActivity.class);
        intent.putExtra(ShowAddressesActivity.EXTRA_MODE, ShowAddressesActivity.PICK_ADDRESS_MODE);
        startActivityForResult(intent, Constants.PICK_ADDRESS_REQUEST_CODE);

    }

    public boolean isAddressEmpty() {
        Address mAddress = SharedPreferencesHelper.getAddress(SharePreferenceKeys.CURRENT_ADDRESS);
        if (mAddress == null) {
            return true;
        } else {
            return false;
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
    }
}
